/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package android.isisufes.home2;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.isisufes.R;
import android.isisufes.util.DBHelper;
import android.isisufes.util.ServerCom;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class FileManager extends ListActivity {
	private SQLiteDatabase db;
	private ListView v;
	private LayoutInflater vi; //	private ViewInflate vi;
	private ArrayAdapter<CharSequence> ssaa;
	private ArrayAdapter<CharSequence> tsaa;
	private RelativeLayout rlt[], rlc[];
	private Cursor c;
	private String spstatus, sptype;
	private DBHelper dbHelper;
	private Dialog d;
	private MyListAdapter mla;
			
    public void onCreate(Bundle icicle) {
    	super.onCreate(icicle);	

    	db = this.openOrCreateDatabase("homedb", MODE_PRIVATE, null);
		dbHelper = new DBHelper();
		dbHelper.onCreate(db);
    	
		buildFileManager();
		filter(null, null, null, null, null);
		listFiles();
		mla = new MyListAdapter(this, vi, rlc, rlt, 0, 70);
		setListAdapter(mla);
		setUpScreenButtons();

    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();

    	if(c != null){
    		c.close();
    	}

    	db.close();
    }
    
	public void buildFileManager() {
		this.setTitle("Join Us! - File Manager");
		
		vi = this.getLayoutInflater(); //vi = this.getViewInflate();	
		v = this.getListView();
		d = new Dialog(v.getContext());

		v.addFooterView(vi.inflate(R.layout.filemanager, null)); //,null));
	}
	
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	MyListAdapter x = (MyListAdapter) getListAdapter();
    	x.toggle(position);
    }
	
	private void filter(String status, String type, String name, String creator, String campaign) {
		String sql = "userid = '" + ServerCom.id + "'";
		
		if(status != null)
			if(status.compareTo("All") != 0)
				sql += " AND status = '" + status + "'";

		if(type != null)
			if(type.compareTo("Any") != 0)
				sql += " AND type = '" + type + "'";
		
		if(name != null)
			if(name.compareTo("") != 0) 
				sql += " AND filename LIKE '%" + name + "%'";
		if(creator != null)
			if(creator.compareTo("") != 0)
				sql += " AND campaigncreator LIKE '%" + creator + "%'";
		
		if(campaign != null)
			if(campaign.compareTo("") != 0)
				sql += " AND campaignname LIKE '%" + campaign + "%'";
				
		c = db.query("fileInfo", null, sql, null, null, null, null);
	}
	
	private void setUpStatusSpinner() {
		String s[] = { "Downloading", "Canceled", "Complete", "All" };
		
		Spinner sp = (Spinner) d.findViewById(R.id.statusspinner);
		ssaa = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item);
        
		for(String i : s) ssaa.add(i);

        ssaa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(ssaa);
        
    	sp.setOnItemSelectedListener(new OnItemSelectedListener() {
    		public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    			spstatus = parent.getSelectedItem().toString();
    		}

			public void onNothingSelected(AdapterView<?> arg) { }
    	});
    }
	
	private void setUpTypeSpinner() {
		String s[] = { "Image", "Sound", "Document", "Video", "Unknown", "Any" };

		Spinner sp = (Spinner) d.findViewById(R.id.typespinner);
		tsaa = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item);
        
		for(String i : s) tsaa.add(i);

        tsaa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(tsaa);
        
    	sp.setOnItemSelectedListener(new OnItemSelectedListener() {
    		public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    			sptype = parent.getSelectedItem().toString();
    		}

			public void onNothingSelected(AdapterView<?> arg) { }
    	});

	}
	
	public void listFiles() {
		if(c == null) {
			rlt = null;
			rlc = null;
			return;
		}
		
		if(c.getCount() == 0) {
			rlt = null;
			rlc = null;
			return;
		}
		
		int rid = 0;
		RelativeLayout rt, rc;
		
		rlt = new RelativeLayout[c.getCount()];
		rlc = new RelativeLayout[c.getCount()];

		for(int i = 0; i < c.getCount(); ++i) {
			c.moveToPosition(i);

			rt = (RelativeLayout) vi.inflate(R.layout.line_template_fm, null); //, null);
			rc = (RelativeLayout) vi.inflate(R.layout.attach_details, null); //, null);
				
			((ImageButton) rc.getChildAt(0)).setImageResource(rid);
			
			String size = c.getString(3);
			String filename = c.getString(5);
			String status = c.getString(6);

			((TextView) rt.getChildAt(0)).setText("Name: "+ filename);
			((TextView) rt.getChildAt(1)).setText("Status: " + status);			

			rlt[i] = rt;

			((TextView) rc.getChildAt(2)).setText("Size: " + size + " bytes");
			((TextView) rc.getChildAt(3)).setText("Campaign: " +  c.getString(4));
			
			rlc[i] = rc;
		}		
	}
	
	private void setFilterScreenButtons() {	
		Button set = (Button) d.findViewById(R.id.setbutton);
		set.setOnClickListener(new OnClickListener() {
			public void onClick(View arg) {			
				String name = ((EditText) d.findViewById(R.id.namefield)).getText().toString();
				String creator = ((EditText) d.findViewById(R.id.creatorfield)).getText().toString();
				String campaign = ((EditText) d.findViewById(R.id.campaignfield)).getText().toString();
				d.dismiss();
				filter(spstatus, sptype, name, creator, campaign);
				listFiles();
				mla = new MyListAdapter(v.getContext(), vi, rlc, rlt, 0, 70);
				FileManager.this.setListAdapter(mla);
			}
		});
		
		Button clear = (Button) d.findViewById(R.id.clearbutton);
		clear.setOnClickListener(new OnClickListener() {
			public void onClick(View arg) {
				d.setContentView(R.layout.filter);
				d.setTitle("Join Us! - Filter Box");
				setUpStatusSpinner();
				setUpTypeSpinner();
				d.show();
				setFilterScreenButtons();
			}
		});
	}
	
	private void setUpScreenButtons() {
		Button open = (Button) v.findViewById(R.id.fm_list_view_factory_open);

		open.setOnClickListener(new OnClickListener() {
			public void onClick(View arg) { 
				int i = 0, f = 0;
				boolean changed = false;

				if(c.getCount() == 0) {
					Toast.makeText(v.getContext(), "There are no files to open!", Toast.LENGTH_SHORT).show();
					return;
				}
				
				for(RelativeLayout r : rlt) {
					if(((CheckBox) r.getChildAt(2)).isChecked()) {
						c.moveToPosition(i);
						if(changed) {
							Toast.makeText(FileManager.this, "Only one file can be opened!", Toast.LENGTH_SHORT).show();
							return;
						}
						else {
							changed = true;
							f = i;
						}

					}
					++i;
				}
				
				if(changed) {
					c.moveToPosition(f);

					if(c.getString(6).compareTo("Complete") != 0) {
						Toast.makeText(FileManager.this, "Only completed downloads can be opened!", Toast.LENGTH_SHORT).show();
						return;
					}

					d.setContentView(R.layout.create_file);
					((EditText) d.findViewById(R.id.create_file_name)).setText(c.getString(5));
					((EditText) d.findViewById(R.id.create_file_name)).setEnabled(false);
					((EditText) d.findViewById(R.id.create_file_desc)).setText(c.getString(9));
					((EditText) d.findViewById(R.id.create_file_desc)).setEnabled(false);

					Cursor cc = db.query("fileContent", null, "idattach = '" + c.getString(0) + "' AND id = '" + ServerCom.id + "'", null, null, null, null);
					
					cc.moveToPosition(0);
					String cont = cc.getString(2);
					cc.close();
					
					((EditText) d.findViewById(R.id.create_file_content)).setText(cont);
					Button ok = (Button) d.findViewById(R.id.create_file_but);
					ok.setText("Ok");
					
					d.show();
					
					ok.setOnClickListener(new OnClickListener() {
						public void onClick(View arg) {
							String cont = ((EditText) d.findViewById(R.id.create_file_content)).getText().toString();
							db.execSQL("UPDATE fileContent SET content = '" + cont + "' WHERE idattach = '" + c.getString(0) + "' AND id = '" + ServerCom.id + "'");
							d.dismiss();
						}
					});	
				}
			}
		});

		Button filter = (Button) v.findViewById(R.id.fm_list_view_factory_filter);

		filter.setOnClickListener(new OnClickListener() {
			public void onClick(View arg) { 
				d.setContentView(R.layout.filter);
				d.setTitle("Join Us! - Filter Box");

				setUpStatusSpinner();
				setUpTypeSpinner();
			
				d.show();
				
				setFilterScreenButtons();

			}
		});

		Button delete = (Button) v.findViewById(R.id.fm_list_view_factory_delete);

		delete.setOnClickListener(new OnClickListener() {
			public void onClick(View arg) {
				int i = 0;
				boolean changed = false;

				if(c.getCount() == 0) {
					Toast.makeText(v.getContext(), "There are no files to delete!", Toast.LENGTH_SHORT).show();
					return;
				}

				
				for(RelativeLayout r : rlt) {
					if(((CheckBox) r.getChildAt(2)).isChecked()) {
						c.moveToPosition(i);
						changed = true;
						db.execSQL("DELETE from fileInfo WHERE userid = '" + ServerCom.id + "' AND idattach = '" + c.getString(0) + "';");
						db.execSQL("DELETE from fileContent WHERE id = '" + ServerCom.id + "' AND idattach = '" + c.getString(0) + "';");
					}
					++i;
				}
				
				if(changed) {
					filter(null, null, null, null, null);
					listFiles();
					mla = new MyListAdapter(v.getContext(), vi, rlc, rlt, 0, 90);
					FileManager.this.setListAdapter(mla);
					setUpScreenButtons();
				}
			}
		});
		
		Button download = (Button) v.findViewById(R.id.fm_list_view_factory_cancel);

		download.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				int i = 0;
				boolean changed = false;

				if(c.getCount() == 0) {
					Toast.makeText(v.getContext(), "There are no downloads to cancel!", Toast.LENGTH_SHORT).show();
					return;
				}

				
				for(RelativeLayout r : rlt) {
					if(((CheckBox) r.getChildAt(2)).isChecked()) {
						c.moveToPosition(i);
						if(c.getString(6).compareTo("Downloading") != 0) {
							Toast.makeText(FileManager.this, "This can be used only with on-going downloads!", Toast.LENGTH_LONG).show();
							return;
						}
						changed = true;
						db.execSQL("UPDATE fileInfo SET status = 'Canceled' WHERE userid = '" + ServerCom.id + "' AND hash = '" + c.getString(0) + "';");
					}
					++i;
				}
				
				if(changed) {
					listFiles();
					mla = new MyListAdapter(v.getContext(), vi, rlc, rlt, 0, 70);
					FileManager.this.setListAdapter(mla);
					setUpScreenButtons();
				}
			}
		});
	}
		
    class AttachView extends LinearLayout {
        public AttachView(Context context, View title, View dialogue, boolean expanded, int selected, int size) {
            super(context);
            
            this.setOrientation(VERTICAL);

            addView(title, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            
            mDialogue = (RelativeLayout)dialogue;
            
            addView(mDialogue, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,size));
            
            mDialogue.setVisibility(expanded ? VISIBLE : GONE);

        }
        
        /**
         * Convenience method to set the title of a SpeechView
         */
        public void setTitle(View title) {
            mTitle=title;
        }
        
        /**
         * Convenience method to set the dialogue of a SpeechView
         */
        public void setDialogue(View view) {
            mDialogue=(RelativeLayout)view;
        }
        
        /**
         * Convenience method to expand or hide the dialogue
         */
        public void setExpanded(boolean expanded) {
            mDialogue.setVisibility(expanded ? VISIBLE : GONE);
        }
        
        @SuppressWarnings("unused")
		private View mTitle;
        private RelativeLayout mDialogue;
    }
    
    // TODO: Confrontar esta classe com a encontrada em MyListAdapter.java
	class MyListAdapter extends BaseAdapter {
		LayoutInflater inflate;
		private View[] mDialogue;
		private View[] mTitles;
		private boolean[] mExpanded;
	    private Context mContext;
	    int size;
		
	    public MyListAdapter(Context con, LayoutInflater vinf, View[] cc, View[] ll, int f, int s) {
	        mContext = con;
	        size = s;
	        inflate = vinf;
	        mDialogue = cc;
	        mTitles = ll;
	        mExpanded = mTitles == null ? null : new boolean[mTitles.length];

	        if(mExpanded != null)
	        	for(int i = 0; i < mTitles.length; ++i) mExpanded[i] = true;
	    }

	    public int getCount() { return mTitles != null ? mTitles.length : 0; }

	    public Object getItem(int p) { return p; }

	    public long getItemId(int p) { return p; }

	    public View getView(int p, View cv, ViewGroup par) {
	    	AttachView av;

	    	if(cv == null)
	    		av = new AttachView(mContext, mTitles[p], mDialogue[p], mExpanded[p], p, size);
	    	else {
	    		av = (AttachView) cv;
	    		av.setTitle(mTitles[p]);
	    		av.setDialogue(mDialogue[p]);
	    		av.setExpanded(mExpanded[p]);
	    	}

	    	return av;
	    }

	    public void toggle(int p) {
	    	Log.d("*****","*********");
	    	if(p < mTitles.length) {
	    		int i;
	    		for(i = 0; i < mTitles.length ; ++i) mExpanded[i]= false;
	    		Log.d("*****","*********"+i);
	    		mExpanded[p] = true;
	    		notifyDataSetChanged();
	    	}
	    }

		public boolean areAllItemsSelectable() {
			// TODO Auto-generated method stub
			return false;
		}

		public boolean isSelectable(int arg0) {
			// TODO Auto-generated method stub
			return false;
		}

		public int getNewSelectionForKey(int currentSelection, int keyCode,
				KeyEvent event) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void registerDataSetObserver(DataSetObserver observer) {
			// TODO Auto-generated method stub
			
		}

		public boolean stableIds() {
			// TODO Auto-generated method stub
			return false;
		}

		public void unregisterDataSetObserver(DataSetObserver arg0) {
			// TODO Auto-generated method stub
			
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(KeyEvent.KEYCODE_BACK == keyCode ) {
			finish();
			return true;
		}
		
		return false;
	}

}